package com.belazy.library.util.compute;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @Description <p> 生成验证码图片工具类</p>
 * @Author chupeng.tang
 * @CreateTime 2023/5/19 17:29
 * @Version 1.0
 */
public class ValidateCodeUtils {
    private static final int WIDTH = 85;
    private static final int HEIGHT = 40;
    private static final int RBG_255 = 255;
    /**
     * <p>生成验证码图片</p>
     * @auhor chupeng.tang
     * @datetime 2023/5/20 11:49
     * @return {@link Map.Entry< String, BufferedImage>} key为code字符串，value位图片
     **/
    public static Map.Entry<String, BufferedImage> generate() {
        //在内存中创建图象
        BufferedImage image = new BufferedImage (WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        //获取图形上下文
        Graphics2D g = image.createGraphics ();

        //设定背景色
        g.setColor (getRandColor (200, 250));
        g.fillRect (0, 0, WIDTH, HEIGHT);
        //设定字体
        g.setFont (new Font ("Times New Roman", Font.PLAIN, 18));
        //随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
        g.setColor (getRandColor (160, 200));
        //生成随机类
        Random random = new Random ();
        int ln = 155;
        for (int i = 0; i < ln; i++) {
            int x = random.nextInt (WIDTH);
            int y = random.nextInt (HEIGHT);
            int xl = random.nextInt (12);
            int yl = random.nextInt (12);
            g.drawLine (x, y, x + xl, y + yl);
        }
        //取随机产生的认证码(4位数字)
        StringBuilder sb = new StringBuilder ();
        int lg = 4;
        for (int i = 0; i < lg; i++) {
            String code = String.valueOf (random.nextInt (10));
            sb.append (code);
            //将认证码显示到图象中
            g.setColor (new Color (20 + random.nextInt (110), 20 + random.nextInt (110), 20 + random.nextInt (110)));
            g.drawString (code, 13 * i + 18, 27);
        }

        Map<String, BufferedImage> map = new HashMap<> (1);
        map.put (sb.toString (), image);

        return map.entrySet ().iterator ().next ();
    }
    /**
     * <p>给定范围获得随机颜色</p>
     * @auhor chupeng.tang
     * @datetime 2023/5/20 11:50
     * @param: fc
     * @param: bc
     * @return {@link Color}
     **/
    private static Color getRandColor(int fc, int bc) {
        Random random = new Random ();
        if (fc > RBG_255) {
            fc = RBG_255;
        }
        if (bc > RBG_255) {
            bc = RBG_255;
        }
        int r = fc + random.nextInt (bc - fc);
        int g = fc + random.nextInt (bc - fc);
        int b = fc + random.nextInt (bc - fc);
        return new Color (r, g, b);
    }

}
